package yxy.game.pm2.command.soloride;

import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.soloridefirstreward;
import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.SoloRideMessage;
import yxy.game.pm2.module.CurrencyHandle;
import yxy.game.pm2.module.soloride.SoloRideModule;

import java.util.Collection;

/** 千里走单骑 千里走单骑领取首通奖励 */
@MessageType(proto = Command.SoloRideFirstReward, classtype = SoloRideMessage.SoloRideFirstRewardRequest.class)
public class CMD_SoloRideFirstReward extends Command<SoloRideMessage.SoloRideFirstRewardRequest> {

	@Override
	public void execute(MessageSource messageSource, SoloRideMessage.SoloRideFirstRewardRequest request) {
		String playerCode = messageSource.getTag();
		int stage = request.getStage();

		SoloRideMessage.SoloRideFirstRewardResponse.Builder response = SoloRideMessage.SoloRideFirstRewardResponse.newBuilder();

		SoloRideModule soloRideModule = SoloRideModule.get(playerCode);
		if (soloRideModule == null) {
			send(messageSource, response, Result.ModuleNotOpen);// 模块没开启
			return;
		}
		try {
			if (soloRideModule.tryLock()) {
				soloridefirstreward data = DataCenter.getData(stage, soloridefirstreward.class);
				if (data == null) {
					send(messageSource, response, Result.InfiniteBoxHasRewarded);// 宝箱数据不存在
					return;
				}

				if (soloRideModule.getBox() >= data.getId()) {
					send(messageSource, response, Result.InfiniteBoxHasRewarded);// 宝箱已领过
					return;
				}
				Collection<Currency> rewards = Currency.create(data.getFirsttype(), data.getFirstid(), data.getFirstnum());
				new CurrencyHandle().addCurrency(playerCode, CCReason.千里单骑, rewards);
				soloRideModule.setBox(data.getId());
				soloRideModule.set();

				response.addAllBox(soloRideModule.rewardBox());
				response.addAllRewards(new CurrencyHandle().packItems(rewards));

				send(messageSource, response, Result.Success);
			}
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		} finally {
			soloRideModule.unlock();
		}
	}

	private void send(MessageSource messageSource, SoloRideMessage.SoloRideFirstRewardResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}